#!/usr/bin/env python
from comm.model.m_admin import *
from comm.tool import *

class BizAdmin:
	def __init__(self):
		pass

	def ListUser(self, start, limit):
		if not start or start<0 : start=0
		if not limit or limit<1 : limit=10
		sess = SessionPapaAdmin()
		list = []
		total = 0
		try:
			total = sess.query(TUser).count()
			list = sess.query(TUser).offset(start).limit(limit).all()
			return (list, total)
		finally:
			sess.close()

	def GetUser(self, uid):
		sess = SessionPapaAdmin()
		try:
			user = sess.query(TUser).filter(TUser.uid==uid).first()
			if user :
				return user
			else:
				raise 'user does not exist'
		finally:
			sess.close()
	
	def AddUser(self, uid, pwd):
		sess = SessionPapaAdmin()
		try:
			sess.save( TUser(uid, Tool.md5(Tool.md5(pwd)) )  )
			sess.commit()
		finally:
			sess.close()
	
	def EditUser(self, uid, pwd):
		sess = SessionPapaAdmin()
		try:
			user = sess.query(TUser).filter(TUser.uid==uid).first()
			if user :
				user.pwdhash = Tool.md5(Tool.md5(pwd)) 
				sess.update( user )
				sess.commit()
			else:
				raise 'user does not exist'
		finally:
			sess.close()

	def RemoveUser(self, uid):
		sess = SessionPapaAdmin()
		try:
			user = sess.query(TUser).filter(TUser.uid==uid).first()
			if user :
				if user.uid=='admin':
					raise 'admin is irremovable'
				sess.delete( user )
				sess.commit()
			else:
				raise 'user does not exist'
		finally:
			sess.close()

if __name__ == '__main__':
	import sys
	if len(sys.argv)>1 and 'recreate'==sys.argv[1] :
		meta.drop_all(egn_papa_admin)
		meta.create_all(egn_papa_admin)
	else:
		ss = SessionPapaAdmin()
		
		#for m in mems:
		#	print m
		for i in range(100):
			ss.save(TUser('usr%02d'%i, '___nothing____'))
		
		ss.commit()
